package com.qf.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;

import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.qf.utils.ErWeiMaUtil;
import org.springframework.stereotype.Component;


@Component
public class AliPayTools2 {

    public static String serverUrl="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    public static String appId="9021000128678689";
    public static String pricateKey="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCahQv7S2GO3XOSOEiejbIkMOXpUC/HQh7rEjUEXPmpyg31N5WK5Snl/O65eyVPbGRpLIDCQ+ZXKVC3BmVTVmkJGfzMOEw8KXrMbFvDUej994N91RCuFuvrKFf0IQ9WHDj9OI1FcVyIo6z1MtdePf4rDZ8G7rfiLkL5iP1LRGzip+fneVFVTGITgp0qDB3eOW9H80qQG/0/7df8nP9oehE476jpLiCjBc0KNbQFg6ajntSUa1yA3ldu64A3q58TSsvQru/5wnAP5jrVb7lv/FfqLgNWr1Rsq5yfbwWm0WWS/RcmjUD/urMXH38twqkIYTPVIxfNqvlrLd6aOgJdNDWxAgMBAAECggEAZYWy2JmvcIFZdKGcPOhWOecSt9difOWZkNM2mDZKJt9Fim7JxydH/v7PDni1i9hopJ2Dv5+DEJNpn8cI/ddRTZSQftEibYjHUNaE9/CyR2K/NwatXeRbfvbTyueJvwbt/pmQYCbaKEB52+RakmXiwADEEnb3xBinEnKKEVDUxZmL5X6erYsmCtTI6IEBFXgJ4HkEgWlnXkk019i4oFReu6HkHZtGkoGb+6DgVSuxMQGHDDjQnEGtvX53t/KSFvqdqudFYtgDATaydG/I+hC17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4m6kzpXJRyZqA3hFAO4MgUwGR1dfYc/QgCo+/2nq0HqgObWPJYi2bhBPZwhFO3xB5KRPd8KwlgqETwFfs1MGABd32Jvgh1YxKjCXF0TqFKOyosICPQPFCVzLBVCssCccznrdBk/K+kzRrgT2QmJv9Th0MRQ7ZjH/MGa0RqD+UW/z4dIKYodEwTmx1oHFjI4CQNJa2OWxPs7OJtu75H3E/ZaUOe/Cv79MrbfpfxbpDF7jEf3Dbsa2F0cs6sHsDmDLovsLYGZdb59URWmgcB/TCLdwIDAQAB";

    public static String pay(String orderId,String goodsName,Integer money,String path){
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl,appId,pricateKey,"json","utf-8",alipayPublicPay,"RSA2");
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
//异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl("http://v9wx7z.natappfree.cc"+path+"/"+orderId);
//同步跳转地址，仅支持http/https
        request.setReturnUrl("http://localhost:8080/home");
/******必传参数******/
        JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", orderId);
//支付金额，最小值0.01元
        bizContent.put("total_amount", money);
//订单标题，不可使用特殊符号
        bizContent.put("subject", goodsName);

/******可选参数******/
//手机网站支付默认传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "QUICK_WAP_WAY");
//bizContent.put("time_expire", "2022-08-01 22:00:00");

//// 商品明细信息，按需传入
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);

//// 扩展信息，按需传入
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        String body = null;
        try {
            body = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return body;
    }


    public static String findPay(String orderId){
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl,appId,pricateKey,"json","utf-8",alipayPublicPay,"RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderId);
//bizContent.put("trade_no", "2014112611001004680073956707");
        request.setBizContent(bizContent.toString());
        try {
            String execute = alipayClient.execute(request).getBody();
            return execute;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     *
     * @param orderId   订单号
     * @param money     金额
     * @return          返回值为Y时退款成功 为N时为退款失败
     */
    public static String tuiKuan(String orderId,Integer money){
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl,appId,pricateKey,"json","utf-8",alipayPublicPay,"RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no",orderId );
        bizContent.put("refund_amount", money);
        bizContent.put("out_request_no", "HZ01RF001");

//// 返回参数选项，按需传入
//JSONArray queryOptions = new JSONArray();
//queryOptions.add("refund_detail_item_list");
//bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());


        AlipayTradeRefundResponse execute = null;
        try {
            execute = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        String fundChange = execute.getFundChange();
        return fundChange;
    }

    /**
     *
     * @param orderId 订单号
     * @param goodsName 商品标题
     * @param money 金额
     * @return 返回值为上传到七牛云的二维码图片链接
     */
    public static String saoma(String orderId,String goodsName,Integer money,String path){
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl,appId,pricateKey,"json","utf-8",alipayPublicPay,"RSA2");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl("http://i7hr86.natappfree.cc"+path+"/"+orderId);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no",orderId);
        bizContent.put("total_amount", money);
        bizContent.put("subject", goodsName);

//// 商品明细信息，按需传入
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);

//// 扩展信息，按需传入
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);

//// 结算信息，按需传入
//JSONObject settleInfo = new JSONObject();
//JSONArray settleDetailInfos = new JSONArray();
//JSONObject settleDetail = new JSONObject();
//settleDetail.put("trans_in_type", "defaultSettle");
//settleDetail.put("amount", 0.01);
//settleDetailInfos.add(settleDetail);
//settleInfo.put("settle_detail_infos", settleDetailInfos);
//bizContent.put("settle_info", settleInfo);

//// 二级商户信息，按需传入
//JSONObject subMerchant = new JSONObject();
//subMerchant.put("merchant_id", "2088000603999128");
//bizContent.put("sub_merchant", subMerchant);

//// 业务参数信息，按需传入
//JSONObject businessParams = new JSONObject();
//businessParams.put("busi_params_key", "busiParamsValue");
//bizContent.put("business_params", businessParams);

//// 营销信息，按需传入
//JSONObject promoParams = new JSONObject();
//promoParams.put("promo_params_key", "promoParamsValue");
//bizContent.put("promo_params", promoParams);

        request.setBizContent(bizContent.toString());

        try {
            AlipayTradePrecreateResponse execute = alipayClient.execute(request);
            String qrCode = execute.getQrCode();
            String s = ErWeiMaUtil.getImgUrl(qrCode);
            return s;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

    }
}
